package main

import (
	"fmt"
	"strings"
)

type AppArgs struct{
	// key 映射
	mapper map[string]string
	// 选项
	Options map[string][]string
	// 命令
	args []string
}

func (th *AppArgs) getOption(key string) string {
	arr := th.Options[key]
	if arr == nil || len(arr) == 0{
		return ""
	}
	return arr[0]
}

func (th *AppArgs) getOptionLast(key string) string {
	arr := th.Options[key]
	if arr == nil || len(arr) == 0{
		return ""
	}
	return arr[len(arr)-1]
}

func (th *AppArgs) getOptionIndex(key string, index int) string {
	arr := th.Options[key]
	if arr == nil || len(arr) < index{
		return ""
	}
	return arr[index]
}




func createAppArgs(sysArgs []string, mapper map[string]string) *AppArgs {
	appArgs := new(AppArgs)
	appArgs.Options = make(map[string][]string)
	appArgs.mapper = mapper


	if sysArgs == nil && len(sysArgs) <= 1 {
		return appArgs
	}

	for i := 1; i<len(sysArgs); i++ {
		arg := sysArgs[i]
		if strings.HasPrefix(arg, "--") { // 以-为前缀的
			item := strings.SplitN(arg, "=", 2)
			key := strings.Replace(item[0], "--", "", 1)
			appArgs.put(key, string(item[1]))
		} else if strings.Contains(arg, "-") { // 包含=号的
			key := strings.Replace(arg, "-", "", 1)
			i++
			if i >= len(sysArgs){
				fmt.Printf("参数【%s】没有合适的值，参数超出\n", key)
				return appArgs
			}
			val := sysArgs[i]
			appArgs.put(key, val)
		} else {
			appArgs.args = append(appArgs.args, arg)
		}
	}
	return appArgs
}

func (th *AppArgs) put(key string, val string)  {
	mkey := th.mapper[key]
	arr := th.Options[mkey]
	if mkey == ""{
		th.Options[key] = append(arr, val)
	} else {
		th.Options[mkey] = append(arr, val)
	}
}


